package com.potato.timetable.ui.main;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.reflect.TypeToken;
import com.potato.timetable.R;
import com.potato.timetable.bean.Course;
import com.potato.timetable.bean.Time;
import com.potato.timetable.db.common.AppDatabase;
import com.potato.timetable.db.common.DBUtil;
import com.potato.timetable.db.obj.ClassDO;
import com.potato.timetable.db.obj.TimeDO;
import com.potato.timetable.ui.config.ConfigActivity;
import com.potato.timetable.ui.coursedetails.CourseDetailsActivity;
import com.potato.timetable.ui.settime.SetTimeActivity;
import com.potato.timetable.ui.editcourse.EditActivity;
import com.potato.timetable.util.AlarmReceiver;
import com.potato.timetable.util.Config;
import com.potato.timetable.util.FileUtils;
import com.potato.timetable.util.Utils;
import com.potato.timetable.util.Vibrate;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private FrameLayout mFrameLayout;
    private TextView mWeekOfTermTextView;
    private ImageView mBgImageView;
    private ImageButton mAddImgBtn;
    private LinearLayout headerClassNumLl;
    private boolean flagUpdateCalendar = false;

    public static List<Course> sCourseList;
    public static Time[] sTimes;

    private List<TextView> mClassTableTvList = new ArrayList<>();
    private TextView[] mClassNumHeaders = null;


    private static final int REQUEST_CODE_COURSE_DETAILS = 0;
    private static final int REQUEST_CODE_COURSE_EDIT = 1;
    private static final int REQUEST_CODE_CONFIG = 3;
    private static final int REQUEST_CODE_SET_TIME = 6;

    private static final int REQ_PER_CALENDAR = 0x11;//日历权限申请

    private OptionsPickerView mOptionsPv;

    private AppDatabase appDatabase;

    public static float VALUE_1DP;//1dp的值

    private static float sCellWidthPx;//课程视图的宽度(px)
    private static float sCellHeightPx;//课程视图的高度;

    private AlarmManager alarmMgr;
    private PendingIntent alarmIntent;

    private static final int INTERVAL = 1000 * 60 * 60 * 24;// 24h

    AlarmManager am;
    PendingIntent pi;
    long time;


    private static final int REQUEST_EXTERNAL_STORAGE = 1;

    private static final String[] PERMISSIONS_STORAGE = {

            "android.permission.READ_EXTERNAL_STORAGE",

            "android.permission.WRITE_EXTERNAL_STORAGE"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        appDatabase = DBUtil.getAppDatabase(this);

        getWritePermission();

        initAlarm();

        int[] weekTextView = new int[]{
                R.id.tv_sun,
                R.id.tv_mon,
                R.id.tv_tues,
                R.id.tv_wed,
                R.id.tv_thur,
                R.id.tv_fri,
                R.id.tv_sat

        };
        mWeekOfTermTextView = findViewById(R.id.tv_week_of_term);
        mAddImgBtn = findViewById(R.id.img_btn_add);
        mBgImageView = findViewById(R.id.iv_bg_main);
        mFrameLayout = findViewById(R.id.fl_timetable);
        headerClassNumLl = findViewById(R.id.ll_header_class_num);


        Config.readFormSharedPreferences(this);//读取当前周信息

        Utils.setPATH(getExternalFilesDir(null).getAbsolutePath() + File.separator + "pictures");

        VALUE_1DP = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
                getResources().getDisplayMetrics());

        float headerClassNumWidth = getResources().getDimension(R.dimen.table_header_class_width);

        setTableCellDimens(headerClassNumWidth);

        int week = getWeekOfDay();

        TextView weekTv = findViewById(weekTextView[week - 1]);
        weekTv.setBackground(getDrawable(R.color.day_of_week_color));

        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);

        initTimetable();

        Utils.setBackGround(this, mBgImageView);
    }

     //本周应该上的课程
    private List<Course> getCoursesNeedToTake() {
        int currentWeek = Config.getCurrentWeek();
        if (getWeekOfDay() == 1) {//周日插入下周课程的日程
            currentWeek++;
        }
        //周日更新下周课程表
        List<Course> tempList = new LinkedList<>();

        for (Course course : sCourseList) {
            if (courseIsThisWeek(course, currentWeek)) {
                tempList.add(course);
            }
        }
        return tempList;
    }




//    private void addClassCalendarEvent(List<Course> courses, final long start) {
//        if (sTimes == null) {
//            return;
//        }
//        final int minute = 1000 * 60;
//        final int hour = minute * 60;
//        final int day = 24 * hour;
//        //Log.d("stimes",courses.size()+"");
//        String[] weeks = new String[]{"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
//        for (Course course : courses) {
//            Log.d("stimes", course.getClassStart() + "");
//            String classStart = sTimes[course.getClassStart() - 1].getStart();
//            String classEnd = sTimes[course.getClassStart() - 1 + course.getClassLength() - 1].getEnd();
//            if (!classStart.isEmpty() && !classEnd.isEmpty()) {
//                String[] strings = classStart.split(":");
//                int startHour = Integer.parseInt(strings[0]);
//                int startMinute = Integer.parseInt(strings[1]);
//                strings = classEnd.split(":");
//                int endHour = Integer.parseInt(strings[0]);
//                int endMinute = Integer.parseInt(strings[1]);
//
//
//            }
//        }
//    }


     //初始化Calendar

    private Calendar initCalendar() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //重置
        // 时
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        // 分
        calendar.set(Calendar.MINUTE, 0);
        // 秒
        calendar.set(Calendar.SECOND, 0);
        // 毫秒
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar;
    }



     //计算课程格子的长宽
    private void setTableCellDimens(float headerWidth) {
        //获取屏幕宽度，用于设置课程视图的宽度
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int displayWidth = displayMetrics.widthPixels;
        int displayHeight = displayMetrics.heightPixels;

        Resources resources = getResources();
        int toolbarHeight = resources.getDimensionPixelSize(R.dimen.toolbar_height);
        int headerWeekHeight = resources.getDimensionPixelSize(R.dimen.header_week_height);

        //课程视图宽度
        sCellWidthPx = (displayWidth - headerWidth) / 7.0f;

        sCellHeightPx = Math.max(sCellWidthPx,
                (displayHeight - toolbarHeight - headerWeekHeight) / (float) Config.getMaxClassNum());
    }


    @SuppressLint("ClickableViewAccessibility")
    private void initFrameLayout() {

        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mFrameLayout.getLayoutParams();
        //设置课程表高度
        layoutParams.height = (int) sCellHeightPx * Config.getMaxClassNum();
        //设置课程表宽度
        layoutParams.width = (int) sCellWidthPx * 7;

        mAddImgBtn.getLayoutParams().height = (int) sCellHeightPx;
        mFrameLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                int event = motionEvent.getAction();
                if (event == MotionEvent.ACTION_UP) {
                    if (mAddImgBtn.getVisibility() == View.VISIBLE) {
                        mAddImgBtn.setVisibility(View.GONE);
                    } else {
                        int x = (int) (motionEvent.getX() / sCellWidthPx);
                        int y = (int) (motionEvent.getY() / sCellHeightPx);
                        x = (int) (x * sCellWidthPx);
                        y = (int) (y * sCellHeightPx);
                        setAddImgBtn(x, y);
                    }
                }
                return true;
            }
        });
    }

    private void initAddBtn() {
        final FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mAddImgBtn.getLayoutParams();
        layoutParams.width = (int) sCellWidthPx;
        layoutParams.height = (int) sCellHeightPx;
        mAddImgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, EditActivity.class);
                int dayOfWeek = layoutParams.leftMargin / (int) sCellWidthPx;
                int classStart = layoutParams.topMargin / (int) sCellHeightPx;
                mAddImgBtn.setVisibility(View.INVISIBLE);
                intent.putExtra(EditActivity.EXTRA_Day_OF_WEEK, dayOfWeek + 1);
                intent.putExtra(EditActivity.EXTRA_CLASS_START, classStart + 1);
                startActivityForResult(intent, REQUEST_CODE_COURSE_EDIT);
            }
        });
    }

    private void setAddImgBtn(int left, int top) {
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mAddImgBtn.getLayoutParams();
        layoutParams.leftMargin = left;
        layoutParams.topMargin = top;
        mAddImgBtn.setVisibility(View.VISIBLE);
    }


    // 获取星期
    private int getWeekOfDay() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DAY_OF_WEEK);
    }

    //获得小时
    public int gethour() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.HOUR);
    }

    //获得分钟
    public int getminute() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MINUTE);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        Intent intent;

        switch (id) {
            case R.id.menu_config://菜单设置
                intent = new Intent(this, ConfigActivity.class);
                startActivityForResult(intent, REQUEST_CODE_CONFIG);
                break;

            case R.id.menu_set_week://菜单设置当前周
                showSelectCurrentWeekDialog();
                break;

            case R.id.menu_append_class://菜单添加课程
                intent = new Intent(this, EditActivity.class);
                startActivityForResult(intent, REQUEST_CODE_COURSE_EDIT);
                break;
            case R.id.menu_set_time://设置上课时间
                startActivityForResult(
                        new Intent(this, SetTimeActivity.class),
                        REQUEST_CODE_SET_TIME);
                break;

            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


     //显示周数列表,让用户从中选择
    private void showSelectCurrentWeekDialog() {

        final int currentWeek = Config.getCurrentWeek();
        final String str = "当前周为：";
        final List<String> items = new ArrayList<>();
        for (int i = 1; i <= Config.getMaxWeekNum(); i++) {
            items.add("第" + i + "周");
        }

        mOptionsPv = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                int selectCurrentWeek = options1 + 1;
                if (selectCurrentWeek != currentWeek) {
                    Config.setCurrentWeek(selectCurrentWeek);
                    updateTimetable();
                    Config.saveCurrentWeek(MainActivity.this);
                }
            }
        }).setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
            @Override
            public void onOptionsSelectChanged(int options1, int options2, int options3) {
                mOptionsPv.setTitleText(str + items.get(options1));
            }
        }).build();

        mOptionsPv.setTitleText("当前周为:" + items.get(currentWeek - 1));

        mOptionsPv.setNPicker(items, null, null);
        mOptionsPv.setSelectOptions(currentWeek - 1);
        mOptionsPv.show();
    }


    //获取读写权限
    private void getWritePermission() {
        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(this,

                    "android.permission.WRITE_EXTERNAL_STORAGE");

            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


     //初始化课表
    private void initTimetable()//根据保存的信息，创建课程表
    {
        //设置标题中显示的当前周数
        mWeekOfTermTextView.setText(String.format(getString(R.string.day_of_week), Config.getCurrentWeek()));

        //读取时间数据
        List<TimeDO> timeDOs=appDatabase.timeDAO().getAll();

        //读取课程数据
        List<ClassDO> classDOs=appDatabase.classDAO().getAll();

        //初始化课程表视图
        initFrameLayout();

        sTimes = new FileUtils<Time[]>().readFromJson(this, FileUtils.TIME_FILE_NAME, Time[].class);
        sCourseList = new FileUtils<ArrayList<Course>>().readFromJson(
                this,
                FileUtils.TIMETABLE_FILE_NAME,
                new TypeToken<ArrayList<Course>>() {
                }.getType());

        //更新节数表头
        updateClassNumHeader();
        //读取失败返回
        if (sCourseList == null) {
            sCourseList = new ArrayList<>();
            return;
        }

        //Log.d("courseNum",String.valueOf(sCourseList.size()));

        int size = sCourseList.size();
        if (size != 0) {
            updateTimetable();
        }

        flagUpdateCalendar = false;

        initAddBtn();
        Log.d("test","是否添加---------------------");
        //setAlarm(gethour(),getminute());
    }


     //选择需要显示的课程
    private List<Course> selectNeedToShowCourse() {
        LinkedList<Course> courseList = new LinkedList<>();

        boolean[] flag = new boolean[12];//-1表示节次没有课程,其他代表占用课程的在mCourseList中的索引

        int weekOfDay = 0;//记录周几

        int size = sCourseList.size();

        for (int index = 0; index < size; index++)//当位置有两个及以上课程时,显示本周上的课程,其他不显示
        {

            Course course = sCourseList.get(index);
            if (!isThisWeekCourseNeedToShow(course.getWeekOfTerm())) {
                continue;
            }

            //Log.d("week", course.getDayOfWeek() + "");
            if (course.getDayOfWeek() != weekOfDay) {
                for (int i = 0; i < flag.length; i++) {//初始化flag
                    flag[i] = false;
                }
                weekOfDay = course.getDayOfWeek();
            }

            int class_start = course.getClassStart();
            int class_num = course.getClassLength();

            int i;

            for (i = 0; i < class_num; i++) {
                if (flag[class_start + i - 1]) {
                    //Log.d("action", "if");
                    if (!courseIsThisWeek(course)) {
                        break;
                    } else {
                        courseList.removeLast();//删除最后一个元素
                        courseList.add(course);
                        for (int j = 0; j < class_num; j++) {
                            flag[class_start + j - 1] = true;
                        }
                        break;
                    }
                }
            }
            if (i == class_num) {
                courseList.add(course);
                for (int j = 0; j < class_num; j++) {
                    flag[class_start + j - 1] = true;
                }
            }
        }
        return courseList;
    }


     //判断非本周课程是否显示
    private boolean isThisWeekCourseNeedToShow(int weekOfTerm) {
        int offset = Config.getMaxWeekNum() - Config.getCurrentWeek();
        //判断是否未到上课时间
        if ((1 << offset) > weekOfTerm) {
            return false;
        }
        return (((1 << (offset + 1) - 1) & weekOfTerm) > 0);
    }

    private void updateClassNumHeader() {

        headerClassNumLl.getLayoutParams().height = (int) sCellHeightPx * Config.getMaxClassNum();
        if (mClassNumHeaders == null) {
            mClassNumHeaders = new TextView[Config.getMaxClassNum()];
            for (int i = 0, len = mClassNumHeaders.length; i < len; i++) {
                mClassNumHeaders[i] = null;
            }
            headerClassNumLl.removeAllViews();
        }
        int height = (int) sCellHeightPx;
        float textSize = getResources().getDimensionPixelSize(R.dimen.class_num_header_text_size);
        StringBuilder stringBuilder = new StringBuilder("12\n22:00\n23:00".length());
        for (int i = 0; i < Config.getMaxClassNum(); i++) {
            TextView textView;
            if (mClassNumHeaders[i] == null) {
                textView = new TextView(this);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, height);

                textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
                textView.setGravity(Gravity.CENTER);
                textView.setTextColor(getResources().getColor(R.color.colorBlack));
                textView.setLayoutParams(layoutParams);
                mClassNumHeaders[i] = textView;
                headerClassNumLl.addView(textView);
            } else {
                textView = mClassNumHeaders[i];
            }
            stringBuilder.append(i + 1);
            textView.getLayoutParams().height = height;
            if (sTimes != null && i < sTimes.length) {
                stringBuilder.append('\n');
                stringBuilder.append(sTimes[i].getStart());
                stringBuilder.append('\n');
                stringBuilder.append(sTimes[i].getEnd());
            }
            textView.setText(stringBuilder.toString());
            stringBuilder.delete(0, stringBuilder.length());
        }
        //如果修改上课节数则删除多余的textview
        for (int i = Config.getMaxClassNum(); i < mClassNumHeaders.length; i++) {
            headerClassNumLl.removeViewAt(i);
        }
        flagUpdateCalendar = true;//更新日程

    }


    // 初始化Alarm
    private void initAlarm(){
        pi=PendingIntent.getBroadcast(this,0,getMsgIntent(),0);
        time=System.currentTimeMillis();
        am= (AlarmManager) getSystemService(ALARM_SERVICE);

    }

    private Intent getMsgIntent(){
//AlarmReceiver 为广播在下面代码中
        Intent intent=new Intent(this,AlarmReceiver.class);
        intent.setAction(AlarmReceiver.BC_ACTION);
        intent.putExtra("msg","闹钟开启");
        return intent;

    }

//设置定时执行的任务

    private void setAlarm(int hour,int minute){
//android Api的改变不同版本中设 置有所不同
        if(Build.VERSION.SDK_INT<19){
            am.set(AlarmManager.RTC_WAKEUP,getTimeDiff(hour,minute),pi);
        }else{
            am.setExact(AlarmManager.RTC_WAKEUP,getTimeDiff(hour,minute),pi);

        }

    }

    public long getTimeDiff(int hour ,int minute){
//这里设置的是当天的15：55分，注意精确到秒，时间可以自由设置
        Calendar ca=Calendar.getInstance();
        ca.set(Calendar.HOUR_OF_DAY,hour);
        ca.set(Calendar.MINUTE,minute);
        ca.set(Calendar.SECOND,0);
        return ca.getTimeInMillis();
    }

    //取消定时任务的执行
    private void cancelAlarm(){
        am.cancel(pi);
    }

     //更新课程表视图
    private void updateTimetable() {
        //设置标题中显示的当前周数
        mWeekOfTermTextView.setText(String.format(getString(R.string.day_of_week), Config.getCurrentWeek()));

        List<Course> courseList = selectNeedToShowCourse();

        int size = courseList.size();
        StringBuilder stringBuilder = new StringBuilder();
        int[] color = new int[]{//课程表循环颜色
                ContextCompat.getColor(this, R.color.item_orange),
                ContextCompat.getColor(this, R.color.item_tomato),
                ContextCompat.getColor(this, R.color.item_green),
                ContextCompat.getColor(this, R.color.item_cyan),
                ContextCompat.getColor(this, R.color.item_purple),
        };

        //Log.d("size", size + "");
        int mClassTableListSize = mClassTableTvList.size();

        for (int i = 0; i < size; i++) {
            Course course = courseList.get(i);
            int class_num = course.getClassLength();
            int week = course.getDayOfWeek() - 1;
            int class_start = course.getClassStart() - 1;
            Log.d("time",sTimes[class_start].getStart()+"-----------");



//            AlarmManager alarmService = (AlarmManager) getSystemService(ALARM_SERVICE);
//            Calendar instance = Calendar.getInstance();
//            instance.set(Calendar.HOUR_OF_DAY, 8);//小时
//            instance.set(Calendar.MINUTE, 0);//分钟
//            instance.set(Calendar.SECOND, 0);//秒
//
//            Intent alarmIntent = new Intent(this, AlarmclockReceive.class);
//            PendingIntent broadcast = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
//            alarmService.setRepeating(AlarmManager.RTC_WAKEUP, instance.getTimeInMillis(), INTERVAL,broadcast);//这里一定要注意，一定要相对时间对应相对时间，

//            AlarmManager alarmManager =
//                    (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//            PendingIntent pendingIntent =
//                    PendingIntent.getService(context, requestId, intent,
//                            PendingIntent.FLAG_NO_CREATE);
//            if (pendingIntent != null && alarmManager != null) {
//                alarmManager.cancel(pendingIntent);
//            }
//
            //谷歌官方
//            Log.d("test","谷歌的测试"+"");
            Context context = MainActivity.this;
//            alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//            Intent intent = new Intent(context, AlarmReceiver.class);
//            alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
//            // Set the alarm to start at approximately 2:00 p.m.
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTimeInMillis(System.currentTimeMillis());
//            calendar.set(Calendar.HOUR_OF_DAY, 15);
//            calendar.set(Calendar.MINUTE,58);

//            Calendar calendar = Calendar.getInstance();
//            calendar.setTimeInMillis(System.currentTimeMillis());
//            calendar.set(Calendar.HOUR_OF_DAY, 16);
//            calendar.set(Calendar.MINUTE,3);
//            calendar.set(Calendar.SECOND, 0);
//            calendar.set(Calendar.MILLISECOND, 0);
//            Intent intent = new Intent(context,AlarmReceiver.class);
//            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
//            AlarmManager am;
//            am = (AlarmManager)context.getSystemService(ALARM_SERVICE);
//            am.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

            // With setInexactRepeating(), you have to use one of the AlarmManager interval
            // constants--in this case, AlarmManager.INTERVAL_DAY.
//            alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
//                    AlarmManager.INTERVAL_DAY, alarmIntent);


//            Calendar calendar = Calendar.getInstance();
//            calendar.setTimeInMillis(System.currentTimeMillis());
//            calendar.set(Calendar.HOUR_OF_DAY, 18);
//            calendar.set(Calendar.MINUTE,0);
//            calendar.set(Calendar.SECOND, 0);
//            calendar.set(Calendar.MILLISECOND, 0);
//            Intent intent = new Intent(context,AlarmReceiver.class);
//            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
//            AlarmManager am;
//            am = (AlarmManager)context.getSystemService(ALARM_SERVICE);
//            am.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);



//            if(sTimes[class_start].getStart()!=null) {
//                String start = sTimes[class_start].getStart();
                //boolean isVirating;
            //setAlarm(gethour(),getminute());

//                //开启震动
//                isVirating = true;
//                Vibrate.vibrate(MainActivity.this, new long[]{1000, 1000, 1000, 1000}, 0);
//                //关闭震动
//                if (isVirating) {
//                    isVirating = false;
//                    Vibrate.virateCancle(MainActivity.this);
//
//                }
            //}

            TextView textView;
            if (i < mClassTableListSize) {
                textView = mClassTableTvList.get(i);
            } else {
                textView = new TextView(this);
                mClassTableTvList.add(textView);
                mFrameLayout.addView(textView);
            }
            setTableCellTextView(textView,
                    class_num, week,
                    class_start);

            setTableClickListener(textView, sCourseList.indexOf(course));

            String name = course.getName();
            if (name.length() > 10) {
                name = name.substring(0, 10) + "...";
            }
            stringBuilder.append("课名:\n");
            stringBuilder.append(name);
            stringBuilder.append("\n教室:\n");
            stringBuilder.append(course.getClassRoom());
            stringBuilder.append("\n老师:\n");
            stringBuilder.append(course.getTeacher());
            //动态设置TextView背景
            GradientDrawable myGrad = new GradientDrawable();
            myGrad.setCornerRadius(5 * VALUE_1DP);

            if (courseIsThisWeek(course))//判断是否为当前周课程，如果不是，设置背景为灰色
            {
                myGrad.setColor(color[i % 5]);
                textView.setText(stringBuilder.toString());
            } else {
                myGrad.setColor(getResources().getColor(R.color.item_gray));
                stringBuilder.insert(0, "[非本周]\n");
                textView.setText(stringBuilder.toString());
            }
            textView.setBackground(myGrad);

            stringBuilder.delete(0, stringBuilder.length());
        }

        //删除多余的课程格
        for (int i = size, len = mClassTableTvList.size(); i < len; i++) {
            mFrameLayout.removeView(mClassTableTvList.get(i));
        }
        flagUpdateCalendar = true;//更新日程
    }



     //设置课程视图的监听
    private void setTableClickListener(TextView textView, final int index)//设置课程视图的监听
    {
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, CourseDetailsActivity.class);
                intent.putExtra(CourseDetailsActivity.KEY_COURSE_INDEX, index);
                startActivityForResult(intent, REQUEST_CODE_COURSE_DETAILS);
            }
        });
    }


     // 设置课程格
    private void setTableCellTextView(TextView textView, int class_num, final int left,
                                      final int top) {

        //Log.d("tablecell", left + "," + top);
        float leftMargin = left * sCellWidthPx;
        float topMargin = top * sCellHeightPx;

        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                (int) (sCellWidthPx - 6 * VALUE_1DP),
                (int) (class_num * sCellHeightPx - 6 * VALUE_1DP));

        layoutParams.topMargin = (int) (topMargin + 3 * VALUE_1DP);
        layoutParams.leftMargin = (int) (leftMargin + 3 * VALUE_1DP);

        //设置对齐方式
        textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.START);
        //设置文本颜色为白色
        textView.setTextColor(getResources().getColor(R.color.colorWhite));
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.timetable_cell_text_size));

        textView.setLayoutParams(layoutParams);
    }


     //是否为本周应该上的课程
    private boolean courseIsThisWeek(Course course) {
        return courseIsThisWeek(course, Config.getCurrentWeek());
    }

    //是否为currentWeek周数应该上的课程

    private boolean courseIsThisWeek(Course course, int currentWeek) {
        return (course.getWeekOfTerm() >> (Config.getMaxWeekNum() - currentWeek) & 0x01) == 1;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQ_PER_CALENDAR) {
            for (int r : grantResults) {
                if (r != PackageManager.PERMISSION_DENIED)
                    finish();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                //更新课程表
                case REQUEST_CODE_COURSE_EDIT:
                case REQUEST_CODE_COURSE_DETAILS:
                    if (data == null)
                        return;
                    boolean update = data.getBooleanExtra(EditActivity.EXTRA_UPDATE_TIMETABLE, false);
                    if (update) {
                        updateTimetable();
                    }
                    break;
                //设置
                case REQUEST_CODE_CONFIG:
                    if (data == null)
                        return;
                    boolean update_bg = data.getBooleanExtra(ConfigActivity.EXTRA_UPDATE_BG, false);
                    if (update_bg)
                        Utils.setBackGround(this, mBgImageView);
                    break;
                //设置时间
                case REQUEST_CODE_SET_TIME:
                    if (data != null && data.getBooleanExtra(SetTimeActivity.EXTRA_UPDATE_Time, false)) {
                        Log.d("update", "更新时间");
                        updateClassNumHeader();
                    }
                    break;
                default:
                    break;
            }
        }
    }


}
